<script>
import commonNav from "@/components/nav/commonNav.vue"
import storage from "@/utils/storage.js"
import { getDeviceList } from '@/api/devicePrint.js'
import moment from 'moment'

	// 标签类型
	const LabelType = {
		Gap: 1, // 间隙纸
		BlackMark: 2, // 黑标纸
		Continuous: 3, // 连续纸
		FixedHole: 4, // 定孔纸
		Transparent: 5 // 透明纸
	}
	
	// 绘制支持的旋转角度
	const LabelRotateType = {
		None: 0,
		Rotate90: 90,
		Rotate180: 180,
		Rotate270: 270
	}
	
	// 换行方式
	const LineModeType = {
		Justified: 1, // 宽高固定，内容自适应（字号/字间距/行间距按比例缩放）
		AutoHeight: 2, // 宽度固定，高度自适应
		Fixed: 4, // 宽高固定，超出部分裁剪
		Adapt: 6, // 宽高固定，内容超过时预设宽高自动缩小
	}
	
	// 条码类型
	const BarCodeType = {
		Code128: 20,
		CodeUPC_A: 21,
		CodeUPC_E: 22,
		Ean8: 23,
		Ean13: 24,
		Code93: 25,
		Code39: 26,
		CodeBar: 27,
		ITF25: 28
	}
	
	// 二维码文字显示位置
	const BarCodeTextPosition = {
		Below: 0, // 下方显示
		Above: 1, // 上方显示
		Hidden: 2, // 不显示
	}
	
	// 二维码类型
	const QrCodeType = {
		QrCode: 31,
		PDF417: 32,
		DataMatrix: 33,
		AZTEC: 34
	}
	
	// 线条类型
	const LineType = {
		Solid: 1, // 实线
		Dotted: 2, // 虚线（默认虚实1:1相间）
	}
	
	// 图形类型
	const GraphType = {
		Round: 1, // 圆形
		Oval: 2, // 椭圆形
		Rectangle: 3, // 矩形
		RoundedRectangle: 4 // 圆角矩形
	}

const jcapi = uni.requireNativePlugin("JCSDK-JCApiModule");

export default {
  components: {
    commonNav
  },
  data() {
    return {
      navTitle: this.$t('home.devicePrint'),
      queryParams: {
        sewingId: this.sewingId,
      },
      currentSewLine: storage.get('currentSewLineInfo') || {
        sewingName: '未选择缝制线'
      },
      list: [],
      connectedDevice: null,
      printModeData: [{name : '热敏', value: 1}, {name: '热转印', value: 2}],
      printModePickerSelectedIndex: 0,
      printMode: 1,
      printDensity: 5,
      labelTypeData: [
        {name : '间隙纸', value: LabelType.Gap},
        {name : '黑标纸', value: LabelType.BlackMark},
        {name : '连续纸', value: LabelType.Continuous}, 
        {name : '定孔纸', value: LabelType.FixedHole}, 
        {name : '透明纸', value: LabelType.Transparent},
        ],
      labelTypePickerSelectedIndex: 0,
      labelType: 1,
			printTasks: [],
			pageInfo: {
				limit: 9,
				page: 1,
				total: 0
			},
			devices: [],
			cardInfo: [
				{ label: this.$t('print.deviceSn'), value: 'deviceSn' },
				{ label: this.$t('print.deviceName'), value: 'deviceName' },
				{ label: this.$t('print.deviceType'), value: 'deviceCategory' },
				{ label: this.$t('print.deviceDate'), value: 'createDate' },
			],
			deviceSn: undefined
    }
  },
  mounted() {
		
  },
  onShow() {
		this.getData()
		this.searchDeviceWithName()
  },
  onLoad(option) {
    this.queryParams.sewingId = option.sewingId
    jcapi.initSDK()
  },
  methods: {
    backToHome() {
      uni.navigateTo({
        url: `/pages/index/index`
      })
    },
    searchDevice(){
      let _this = this
			uni.openBluetoothAdapter({ // 确认蓝牙是否打开
				success(r) {
					console.log(r, 'success');
					uni.showLoading({
						title: "搜索中..."
					})

					// 未授予蓝牙相关权限和未打开手机定位会搜索不到设备
					jcapi.getBluetoothDevices(function(r){
						console.log("device~~~:" + JSON.stringify(r))
						// 搜索到设备回调
						uni.hideLoading()
						_this.list = r
					})
        },
        fail: (err) => {
          //未打开
          uni.showToast({ icon: "none", title: "查看手机蓝牙是否打开" });
        }
			})
    },
    searchDeviceWithName(){
      let _this = this
      uni.openBluetoothAdapter({ // 确认蓝牙是否打开
        success(r) {
          uni.showLoading({
            title: _this.$t('print.search')
          })
          // 未授予蓝牙相关权限和未打开手机定位会搜索不到设备
          jcapi.getBluetoothDevicesWithName({
            "name": ["b32", "B21", "M2"] // 添加需要过滤的机型
          },function(r){
            console.log("device:" + JSON.stringify(r))
            // 搜索到设备回调
            uni.hideLoading()
		
            _this.list = r;
          })
        },
        fail(e) {
          uni.showModal({
            confirmText: _this.$t('print.openFailed')
          })
          console.log("开启蓝牙设备失败" + e)
        }
      })
    },
    disconnectPrinter() {
      jcapi.close()
      console.log('断开连接')
      this.connectedDevice = null
    },
    moveHandle() {},
    tapQuery(item) {
			console.log("🚀 ~ file: index.vue:178 ~ tapQuery ~ item:", item)
			// 连接打印机
			let _this = this;
			jcapi.openPrinterByDevice({
				address: item.address,
				name: item.name
			}, function(r) {
				uni.showToast({
					title: (r.code == 0) ? _this.$t('print.connectSuccess') : _this.$t('print.connectFail'),
					duration: 2 * 1000
				})
				if(r.code == 0) {
					_this.connectedDevice = item
				}
			})
		},
		printTextLabel() {
			let that = this

			let datas = this.devices.filter(item => item.select)
			datas = datas.map(device => {
				return [
					{ label: this.$t('print.deviceSn'), value: device.deviceSn },
					{ label: this.$t('print.deviceType'), value: device.deviceCategory },
					{ label: this.$t('print.deviceDate'), value: moment(device.createDate).format('YYYY-MM-DD') },
				]
			})

			datas.forEach((data, idx) => {
				// 初始化画板
				jcapi.initDrawingBoard({
					width: 50,
					height: 30,
					rotate: 0,
				});				
				// 绘制文字
				data.forEach((item, idx) => {
					jcapi.drawLabelGraph({
						x: 1,
						y: 2.2 + (idx * 6),
						width: 28,
						height: 6.4,
						graphType: 4, // 1 圆形 2 椭圆 3 矩形 4 圆角矩形
						rotate: 0,
						cornerRadius: 0.4,
						lineWidth: 0.2,
						lineType: 1, // 1 实线 2 虚线
					})
					jcapi.drawLabelLine({
						x: 11.6,
						y: 2.3 + (idx * 6),
						width: 0.2,
						height: 5.87,
						rotate: 0,
						lineType: 1
					})
					jcapi.drawLabelText({
						x: 1.8,
						y: 3.7 + (idx * 6),
						width: 14,
						height: 20,
						value: `${item.label}`,
						fontSize: 2.2,
						rotate: 0,
						lineMode: LineModeType.AutoHeight,
						lineSpace: 0,
						letterSpace: 0,
						textAlignHorizontal: 0, // 0 左对齐 1 水平居中 2 右对齐
						textAlignVertical: 1, // 0 顶部对齐 1 垂直居中 2 底部对齐
					})
					jcapi.drawLabelText({
						x: 12.2,
						y: 3.68 + (idx * 6),
						width: 16,
						height: 20,
						value: item.value,
						fontSize: 2.5,
						rotate: 0,
						lineMode: LineModeType.AutoHeight,
						lineSpace: 0,
						letterSpace: 0,
						textAlignHorizontal: 0, // 0 左对齐 1 水平居中 2 右对齐
						textAlignVertical: 1, // 0 顶部对齐 1 垂直居中 2 底部对齐
					})
				})
				jcapi.drawLabelText({
					x: 1.8,
					y: 22.18,
					width: 48,
					height: 20,
					value: that.$t("print.tips1"),
					fontSize: 2.2,
					rotate: 0,
					lineMode: LineModeType.AutoHeight,
					lineSpace: 0,
					letterSpace: 0,
					textAlignHorizontal: 0, // 0 左对齐 1 水平居中 2 右对齐
					textAlignVertical: 1, // 0 顶部对齐 1 垂直居中 2 底部对齐
				})
				jcapi.drawLabelText({
					x: 1.8,
					y: 25.18,
					width: 48,
					height: 20,
					value: that.$t("print.tips2"),
					fontSize: 2.2,
					rotate: 0,
					lineMode: LineModeType.AutoHeight,
					lineSpace: 0,
					letterSpace: 0,
					textAlignHorizontal: 0, // 0 左对齐 1 水平居中 2 右对齐
					textAlignVertical: 1, // 0 顶部对齐 1 垂直居中 2 底部对齐
				})
				// 打印二维码
				jcapi.drawLabelQrCode({
					x: 30,
					y: 2,
					width: 18,
					height: 18,
					value: data[0].value,
					rotate: 0,
					codeType: QrCodeType.QrCode,
				});
				// 生成打印数据
				let imageJsonObj = jcapi.generateLabelJson()
				that.printTasks.push(imageJsonObj)

				console.log('打印数据', idx);
			})
		},
		printQrCode() {
			// 初始化画板
			// jcapi.initDrawingBoard({
			// 	width: 50,
			// 	height: 20,
			// 	rotate: 0
			// });				
			// 绘制二维码
			jcapi.drawLabelQrCode({
				x: 36,
				y: 8,
				width: 12,
				height: 12,
				value: "10380150011",
				rotate: 0,
				codeType: QrCodeType.QrCode,
			});
			// 生成打印数据
			let imageJsonObj = jcapi.generateLabelJson()
			// 设置打印任务
			// jcapi.startJob({
			// 	totalCount: 1,
			// 	density: this.printDensity,
			// 	labelType: this.labelType,
			// 	printMode: this.printMode,
			// },function(r){
			// 	if(r.code == 0) {
			// 		// 打印数据
			// 		jcapi.printData(imageJsonObj, {
			// 			"printQuantity": 1,
			// 		}, function(r) {
			// 			if (r.code == 0) {
			// 				console.log("打印成功")
			// 			} else {
			// 				console.log("打印失败")
			// 			}
			// 		})
			// 	} else {
			// 		console.log("设置打印任务失败")
			// 	}
			// })
		},
		async getData() {
			try {
				const params = {
					limit: this.pageInfo.limit,
					page: this.pageInfo.page,
					snOrName: this.deviceSn || ''
				}
				console.log(params, 'params');
				const res = await getDeviceList(params)

				if (+res.code === 0) {
					this.pageInfo.total = res.data.total
					res.data.list.forEach(item => item.select = false)
					this.devices = res.data.list
				}
				console.log(res, 'res');
			} catch (error) {
				console.log(error);
			}
		},
		pageChange({type, current}) {
      this.pageInfo.page = current
      console.log(type, 'type');
      console.log(current, 'current');
      this.getData()
    },
		changeDeviceSelecStatus(device) {
			device.select = !device.select
		}
  },
	watch: {
		printTasks: {
			handler(list) {
				let that = this
				if (list.length > 0) {
						console.log(list.length);
						const target = list[0]
						// 设置打印任务
						jcapi.startJob({
							totalCount: 1,
							density: this.printDensity,
							labelType: this.labelType,
							printMode: this.printMode,
						},function(r){
							if(r.code == 0) {
								// 打印数据
								jcapi.printData(target, {
									"printQuantity": 1,
								}, function(r) {
									if (r.code == 0) {
										console.log("打印成功")
										setTimeout(() => {
											that.printTasks.shift()
										}, 3000)
									} else {
										console.log("打印失败")
									}
								})
							} else {
								console.log("设置打印任务失败")
							}
						})
				}
			},
			deep: true
		},
		list: {
			handler(arr) {
				if (arr.length) {
					this.tapQuery(arr[arr.length - 1])
				}
			}
		}
	}
}

</script>

<template>
  <view class="page">
    <commonNav :currentSewLine="currentSewLine.sewingName" :navTitle="navTitle" @backRouter="backToHome" />
		
    <view class="content">
			<text class="text-style" id="statusTips"> {{connectedDevice ? ( $t("print.connectedToPrinter") + ': ' + connectedDevice.name) : $t("print.notConnect")}}</text>
			<view class="searchBar">
				<u-input v-model="deviceSn" :placeholder="$t('print.enterSn')"></u-input>
				<button type="primary" @click="getData" class="btn">{{ $t("print.query") }}</button>
			</view>
			<view>
				<button type="primary" @click="searchDeviceWithName()" class="btn">{{ $t("print.searchDevice") }}</button>
				<button type="primary" @click="disconnectPrinter()" class="btn">{{ $t("print.disconnect") }}</button>
				<button v-if="connectedDevice" type="primary" @click="printTextLabel()" class="btn">{{ $t("print.print") }}</button>
			</view>
		</view>

    <view>
      <view class="uni-scroll_box">
				<view
					class="uni-list-box"
					v-for="(item, index) in list"
					:key="index"
					@click="tapQuery(item)"
				>
					<view class="uni-list_name">{{ $t("print.name") }}:{{ item.name }}</view>
					<view class="uni-list_item">UUID:{{ item.address }}</view>
				</view>
      </view>

			<view class="devices">
				<view v-for="device in devices" class="device" :class="device.select ? 'selectDevice' : ''" :key="device.id" @click="() => changeDeviceSelecStatus(device)">
					<view v-for="item in cardInfo" class="deviceItem" :key="item.value">
						<view class="label">{{ item.label }}: </view>
						<view class="value">{{ device[item.value] }}</view>
					</view>
				</view>
			</view>
			<view class="paginationBox">
        <uni-pagination 
          :total="pageInfo.total" 
          :current="pageInfo.page"
          :pageSize="pageChange.limit"
          @change="pageChange"
          :showIcon="true"
        ></uni-pagination>
      </view>
    </view>
  </view>
</template>


<style lang="scss" scoped>
.page {
	width: 100%;
}

.content {
	padding: 150rpx 24rpx 0;
	display: flex;
	justify-content: space-between;
}

.searchBar {
	display: flex;
}

.btn {
	padding: 0 24rpx;
	display: inline-block;
	margin-left: 32rpx;
}

.uni-scroll_box {
	white-space: nowrap;
	width: 100%;
	height: 140rpx;
	padding-left: 32rpx;
	display: flex;
	flex-direction: row;
}

.uni-list-box {
	margin-right: 48rpx;
	border-radius: 6px;
	border: 1px solid #efefef;
  box-shadow: 0px 2px 6px 0px #f9f9f9;
	padding: 24rpx;
}

.devices {
	display: grid;
	grid-template-columns: repeat(3, 1fr);
	gap: 28rpx;
	padding: 24rpx;
}

.device {
	border-radius: 12rpx;
	border: 2rpx solid #efefef;
	box-shadow: 2px 2px 4px 4px #efefef;
	padding: 16rpx;
	line-height: 48rpx;
}

.selectDevice {
	background: #1890ff;
	color: #fff;
}

.deviceItem {
	display: flex;
}

.label {
	width: 192rpx;;
}

.paginationBox {
	padding-top: 8px;
	padding-right: 32px;
	display: flex;
	justify-content: flex-end;
}
</style>